package pers.hxy.lookweather.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.util.Log;

/**
 * 检查网络状态
 */
public class NetworkStateUtil {
    private static final String TAG = "NetworkStateUtil";

    /**
     *
     * @param context context
     * @return wifi或移动网络是否可用
     */
    public static boolean isWifiOrMobileAvailable(Context context) {
        int type = getAllAvailableNetworkType(context);
        return hasType(type, ConnectivityManager.TYPE_WIFI) || hasType(type, ConnectivityManager.TYPE_MOBILE);
    }

    /**
     * @param context context
     * @return wifi是否可用
     */
    public static boolean isWifiAvailable(Context context) {
        return hasType(getAllAvailableNetworkType(context), ConnectivityManager.TYPE_WIFI);
    }

    /**
     * @param context context
     * @return 移动网络是否可用
     */
    public static boolean isMobileAvailable(Context context) {
        return hasType(getAllAvailableNetworkType(context), ConnectivityManager.TYPE_MOBILE);
    }

    /**
     * 获取所有可用的网络类型，
     * 比如wifi可用，ConnectivityManager.TYPE_WIFI=1，那么state第1位为1，
     * 检查wifi是否可用就可以使用state & (1 << ConnectivityManager.TYPE_WIFI) != 0  来判断。
     * @param context context
     * @return state
     */
    private static int getAllAvailableNetworkType(Context context) {
        int state = 0;
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        for (Network network : connectivityManager.getAllNetworks()) {
            NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
            if (networkInfo != null && networkInfo.isAvailable()) {
                state |= 1 << networkInfo.getType();
            }
        }
        return state;
    }

    /**
     * @param state 网络状态，每一位表示一种网络类型的状态
     * @param type 网络类型
     * @return state的第type位是否为1
     */
    private static boolean hasType(int state, int type) {
        return (state & (1 << type)) != 0;
    }
}
